package com.ssk.sh.web.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ssk.sh.core.enums.ChatTypeEnum;
import com.ssk.sh.dto.ChatsDto;
import com.ssk.sh.model.Chats;
import com.ssk.sh.model.Workspaces;
import com.ssk.sh.service.IChatsService;
import com.ssk.sh.service.IWorkspacesService;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ssk
 * @since 2025-06-12
 */
@RestController
@RequestMapping("/chats")
@Tag(name = "Chats", description = "Chats")
@Log4j2
@AllArgsConstructor
public class ChatsController {

    final IChatsService chatsService;
    final IWorkspacesService workspacesService;

    @PostMapping("/page")
    Flux<PageInfo<ChatsDto>> getChats() {
        Workspaces workspaces = new Workspaces();
        workspaces.setName("default");
        workspaces.setOwnerId(0L);
        QueryWrapper<Workspaces> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "default");
        Workspaces one = workspacesService.getOne(
                queryWrapper
        );
        if (one == null) {
            boolean save = workspacesService.save(
                    workspaces
            );
        }
        one = workspacesService.getOne(
                queryWrapper
        );
        for (int i = 0; i < 2; i++) {
            Chats chats = new Chats();

            chats.setWsId(one.getId());
            chats.setName(RandomStringUtils.insecure().nextAlphanumeric(10));
            chats.setType(ChatTypeEnum.SINGLE);
            List<Long> members = new ArrayList<>();
            members.add(RandomUtils.nextLong(1, 100));
            members.add(RandomUtils.nextLong(1, 100));

            chats.setMembers(members);

            chatsService.save(chats);
            log.info("{}", JSON.toJSONString(chats, true));
        }

        return chatsService.page(2, 10).cache();

    }


    @PostMapping("/get")
    Mono<ChatsDto> get() {
        return Mono.just(chatsService.getChatsDto());

    }
}
